package com.xu.wemall.commons.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.xu.wemall.commons.enums.ResultEnum;
import com.xu.wemall.commons.exceptions.TokenException;
import com.xu.wemall.commons.utils.JwtUtils;
import com.xu.wemall.commons.components.PassToken;
import com.xu.wemall.entry.User;
import com.xu.wemall.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
@Component
public class JwtAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService iUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 检查是否有passtoken注解，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        } else {  //检查全部
            // 从请求中取出token,这里需要和前端约定好把jwt放到token
            String token = request.getHeader("Authorization");
            log.info("被JWT拦截需要验证");
            if (StringUtils.isEmpty(token)) {
                throw new TokenException(ResultEnum.TOKEN_EXCEPTION);
            }

            //获取token中的userId
            String userId = JwtUtils.getAudience(token);
            User user = iUserService.getById(Long.parseLong(userId));
            if (user == null) {
                throw new Exception("用户不存在");
            }

            try {
                // 验证token
                JwtUtils.verifyToken(token, userId);
            } catch (SignatureVerificationException e) {
                log.error("无效签名，错误是：{}", e);
                return false;
            } catch (TokenExpiredException e) {
                log.error("token过期，错误是：{}", e);
                return false;
            } catch (AlgorithmMismatchException e) {
                log.error("token算法不一致，错误是：{}", e);
                return false;
            } catch (Exception e) {
                log.error("token无效，错误是：{}", e);
                return false;
            }
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView)
            throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex)
            throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

